
var button = document.querySelector('[name="button"]')
button.onclick = function () {
    var username = document.querySelector('[name="username"]')
    var password = document.querySelector('[name="password"]')
    var rpassword = document.querySelector('[name="rpassword"]')
    var nickname = document.querySelector('[name="nickname"]')
    console.log(username.value);
    // var reg = /^[a-z0-9]\d{5,11}$/
    var reg = /^[a-z0-9]\w{4,11}$/
    if (!reg.test(username.value)) {
        alert("用户名不符合规范！")
        return false
    }
    var rag = /\w{6,12}/
    if (!rag.test(password.value)) {
        alert("密码不符合规范！")
        return false
    }
    if (rpassword.value !== password.value) {
        alert("两次输入的密码必须保持一致！")
        return false
    }
    if (nickname.value === '') {
        alert("昵称不可为空！")
        return false
    }
    //提交数据
    var xhr = new XMLHttpRequest;
    xhr.open('post', 'http://localhost:8888/users/register')
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
    xhr.send(`username=${username.value}&password=${password.value}&rpassword=${rpassword.value}&nickname=${nickname.value}`)
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                var res = xhr.responseText
                console.log(res);
                res = JSON.parse(res)
                console.log(res);
                var { code, message } = res
                alert(message)
                if (code === 1) {
                    location.href="login.html"
                }
            }
        }
    }
}

